package mybitree;
import static java.lang.Math.*;

public class Node {
    private String name;
    private Node parent;
    private Node left, right;

    public Node(String data) {
        this.name = data;
    }

    public Node addChildNode(String data) throws NodeIsFullException {
        if ((left != null) && (right != null)) {
            throw new NodeIsFullException();
        }
        Node child = new Node(data);
        child.parent = this;
        if (left == null) {
            left = child;
        } else {
            right = child;
        }
        return child;
    }

    public int getHeight() {
        Node root = getRootOf(this);
        return getCountOfDescendants(root, 0);
    }

    private int getCountOfDescendants(Node node, int level) {
        int leftCount = level, rightCount = level;
        if (node.left != null) {
            leftCount = getCountOfDescendants(node.left, level + 1);
        }
        if (node.right != null) {
            rightCount = getCountOfDescendants(node.right, level + 1);
        }
        return max(leftCount, rightCount);
    }

    private Node getRootOf(Node node) {
        while (node.parent != null) {
            node = node.parent;
        }
        return node;
    }

    @Override
    public String toString() {
        String string = name;
        if ((left == null) && (right == null)) {
            return name + " doesn't contain anything";
        } else if ((left != null) && (right != null)) {
            return String.format("<%1s> has <%2s> and <%3s>", name, left.name, right.name);
        } else if (left != null) {
            return String.format("<%1s> has <%2s>", name, left.name);
        }
        return String.format("<%1s> has <%2s>", name, right.name);
    }
}
